<?php

namespace App\Http\Resources;

use App\Helpers\BaseResource;

class DocPage extends BaseResource
{
    public function toArray($request)
    {
        if ($this->rs_type == 'open') {
            return $this->edit();
        }
        if ($this->rs_type == 'collect') {
            return $this->collect();
        }
        return $this->filterFields([
            'id' => hashid_encode($this->id),
            'parent_id' => $this->parent_id > 0 ? hashid_encode($this->parent_id) : '0',
            'title' => $this->title,
            'is_try' => (boolean)$this->is_try,
            'is_group' => (boolean)$this->is_group,
            'content' => \App\Models\DocPage::getContent($this),
            'updated_format' => $this->updated_at->diffForHumans(),
            'updated_time' => (string)$this->updated_at,
            'link' => urlencode(config('wx.web_host') . 'doc-page?id=' . hashid_encode($this->id)),
            'doc' => $this->whenLoaded('doc', function () {
                $docRes = Doc::make($this->doc);
                $docRes = $this->get_relate_data('doc', $docRes);
                return $docRes;
            }),


        ]);
    }

    public function edit()
    {
        return $this->filterFields([
            'id' => hashid_encode($this->id),
            'parent_id' => $this->parent_id > 0 ? hashid_encode($this->parent_id) : '0',
            'title' => $this->title,
            'is_try' => (boolean)$this->is_try,
            'is_group' => (boolean)$this->is_group,
            'content' => $this->content ?? " ",
            'updated_format' => $this->updated_at->diffForHumans(),
            'updated_time' => (string)$this->updated_at,
            'doc' => $this->whenLoaded('doc', function () {
                $docRes = Doc::make($this->doc);
                $docRes = $this->get_relate_data('doc', $docRes);
                return $docRes;
            })
        ]);
    }

    public function collect()
    {
        return $this->filterFields([
            'id' => hashid_encode($this->id),
            'source' => $this->source,
            'source_key' => $this->source_key,
        ]);
    }
}
